import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service

if __name__ == '__main__':
    url = "http://www.lagou.com"
    # Service的参数是驱动文件的路径
    service = Service('chromedriver.exe')
    brower = webdriver.Chrome(service=service)
    brower.get(url)
    # 执行JS代码
    brower.execute_script("""
        var element=document.querySelector('.loginBar__3S_rT');
        element.parentElement.removeChild(element)
    """
                          )
    element = brower.find_element(By.XPATH, '//*[@id="search_input"]')
    element.send_keys('Python', Keys.ENTER)
    # browser.window_handles可以理解为切换的一个右一个窗口，这里的-1表示选择最后一个
    brower.switch_to.window(brower.window_handles[-1])

    # 登录
    switch_code = brower.find_element(By.XPATH, '//*[@id="lg-passport-box"]/div/div[2]/div/div[1]/div[2]')
    switch_code.click()
    phone_input = brower.find_element(By.XPATH, '//*[@id="lg-passport-box"]/div/div[2]/div/div[2]/div/div[2]/div[1]/input')
    send = brower.find_element(By.XPATH, '//*[@id="lg-passport-box"]/div/div[2]/div/div[2]/div/div[2]/div[2]/div/button')
    code_input = brower.find_element(By.XPATH, '//*[@id="lg-passport-box"]/div/div[2]/div/div[2]/div/div[2]/div[2]/input')
    agree = brower.find_element(By.XPATH, '//*[@id="lg-passport-box"]/div/div[2]/div/div[4]/div[2]/div')
    login = brower.find_element(By.XPATH, '//*[@id="lg-passport-box"]/div/div[2]/div/div[3]/button')
    phone_input.send_keys('18534989116')
    send.click()
    value = input('输入验证码！')
    code_input.send_keys(value)
    agree.click()
    login.click()

    time.sleep(3)
    element = brower.find_element(By.XPATH, '//*[@id="search_input"]')
    element.send_keys('Python', Keys.ENTER)
    brower.switch_to.window(brower.window_handles[-1])
    link_list = brower.find_elements(By.XPATH, '//*[@id="openWinPostion"]')
    tag = False
    for record in link_list:
        while True:
            try:
                if tag:
                    continue
                record.click()
                # 切换到指定页面
                brower.switch_to.window(brower.window_handles[-1])
                element = brower.find_element(By.XPATH, '//*[@id="container"]/div[1]')
                print(element.text)
                brower.close()
                brower.switch_to.window(brower.window_handles[-1])
                time.sleep(2)
                tag = True
            except Exception:
                print('发生错误')

    value = input('输入验证码！')
